package com.hx.springboot1.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hx.springboot1.dao.*;
import com.hx.springboot1.pojo.dto.AccountListDTO;
import com.hx.springboot1.pojo.dto.IndexDTO;
import com.hx.springboot1.pojo.dto.RoleNameDTO;
import com.hx.springboot1.pojo.entity.TabUser;
import com.hx.springboot1.pojo.vo.IndexVO;
import com.hx.springboot1.service.UserService;
import com.hx.springboot1.utils.ResultMsg;
import com.hx.springboot1.utils.checkPwdUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private StuDao stuDao;
    @Autowired
    private CollegeDao collegeDao;
    @Autowired
    private TeacherDao teacherDao;

    @Override
    public TabUser login(String username){
        TabUser login = userDao.login(username);
        return login;
    }
    @Override
    public IndexVO userInfo(String username){
        UserDetails user = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        IndexDTO indexDTO = new IndexDTO();
        TabUser tabUser = userDao.login(username);
        int size = user.getAuthorities().size();
        if (size==1){
            indexDTO.setId(stuDao.selectByUserId(tabUser.getUserId()).getStuId());
            indexDTO.setName(stuDao.selectByUserId(tabUser.getUserId()).getStuName());
            indexDTO.setSex(stuDao.selectByUserId(tabUser.getUserId()).getStuSex());
            indexDTO.setCollege(collegeDao.selectById(stuDao.selectByUserId(tabUser.getUserId()).getCollegeId()).getCollegeName());
        }else if (size==2){
            indexDTO.setId(teacherDao.selectByUserId(tabUser.getUserId()).getTeacherId());
            indexDTO.setName(teacherDao.selectByUserId(tabUser.getUserId()).getTeacherName());
            indexDTO.setSex(teacherDao.selectByUserId(tabUser.getUserId()).getTeacherSex());
            indexDTO.setCollege(collegeDao.selectById(teacherDao.selectByUserId(tabUser.getUserId()).getCollegeId()).getCollegeName());
        }else if (size==3){
            indexDTO.setId(tabUser.getUserId());
            indexDTO.setName("管理员");
            indexDTO.setCollege("admin");
            indexDTO.setSex("admin");
        }
        indexDTO.setRegisterTime(tabUser.getRegisterTime());

        Date registerTime = indexDTO.getRegisterTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String date = sdf.format(registerTime);
        /* VO 视图层需要的模型对象。 从DTO转换而来，大体上和DTO类似。 */
        IndexVO indexVO = new IndexVO(indexDTO.getId(),indexDTO.getName(),indexDTO.getSex(),indexDTO.getCollege(),date);
        return indexVO;
    }

    @Override
    public PageInfo selectAllUser(String searchName, Integer pageNum, Integer pageSize) {
        List<AccountListDTO> allUser = new ArrayList<>();
        RoleNameDTO roleNameDTO = new RoleNameDTO();
        int pn = 1;
        int ps = 10;
        if (pageNum!=null){
            pn = pageNum;
        }
        if (pageSize!=null){
            ps = pageSize;
        }
        //   PageHelper  要在查询之前使用
        PageHelper.startPage(pn,ps);
        if (StringUtils.isEmpty(searchName)){
            List<TabUser> tabUsers = userDao.selectAllUser();
            for (TabUser tabUser : tabUsers) {
                AccountListDTO accountListDTO = new AccountListDTO();
                accountListDTO.setUserId(tabUser.getUserId());
                accountListDTO.setUsername(tabUser.getUsername());
                accountListDTO.setRegisterTime(tabUser.getRegisterTime());
                accountListDTO.setUserState(tabUser.getUserState());
                roleNameDTO = roleDao.selectRoleName(tabUser.getUserId());
                if (roleNameDTO==null){
                    accountListDTO.setRoleName("");
                }else {
                    accountListDTO.setRoleName(roleNameDTO.getRoleName());
                }
                allUser.add(accountListDTO);
            }
            log.info("用户{}点击accountList页面",SecurityContextHolder.getContext().getAuthentication().getName());
        }else {
            searchName = "%"+searchName+"%";
            List<TabUser> tabUsers = userDao.selectAllUserByName(searchName);
            for (TabUser user : tabUsers) {
                AccountListDTO accountListDTO = new AccountListDTO();
                accountListDTO.setUserId(user.getUserId());
                accountListDTO.setUsername(user.getUsername());
                accountListDTO.setRegisterTime(user.getRegisterTime());
                accountListDTO.setUserState(user.getUserState());
                roleNameDTO = roleDao.selectRoleName(user.getUserId());
                if (roleNameDTO==null){
                    accountListDTO.setRoleName("");
                }else {
                    accountListDTO.setRoleName(roleNameDTO.getRoleName());
                }
                allUser.add(accountListDTO);
            }
            log.info("{}查询了用户{}的信息",SecurityContextHolder.getContext().getAuthentication().getName(),searchName);
        }
        PageInfo<AccountListDTO> pageInfo = new PageInfo<>(allUser);
        return pageInfo;
    }

    @Override
    public void updateUserState(String state, String id) {
        userDao.updateUserState(Integer.parseInt(state),Integer.parseInt(id));
    }

    @Override
    public ResultMsg resetPwd(Integer userId) {
        try {
            TabUser tabUser = userDao.selectById(userId);
            userDao.resetPwd(tabUser.getUsername(),userId);
            return new ResultMsg("重置成功！",true);
        }catch (Exception e){
            e.printStackTrace();
            return new ResultMsg("重置失败！",false);
        }
    }

    @Override
    public ResultMsg updatePWD(Integer userId, String newPWD) {
        if (userId!=null){
            TabUser tabUser = userDao.selectById(userId);
            if (newPWD.equals(tabUser.getPassword())){
                return new ResultMsg("新密码不能与原密码相同！",false);
            }
        }
        int i = userDao.updatePWD(userId, newPWD);
        if (i>0){
            return new ResultMsg("修改密码成功！",true);

        }
        return new ResultMsg("密码修改失败！",false);
    }
}

